package cn.bugstack.mybatis.scripting.defaults;

import cn.bugstack.mybatis.mapping.BoundSql;
import cn.bugstack.mybatis.mapping.MappedStatement;
import cn.bugstack.mybatis.mapping.ParameterMapping;
import cn.bugstack.mybatis.reflection.MetaObject;
import cn.bugstack.mybatis.session.Configuration;
import cn.bugstack.mybatis.type.JdbcType;
import cn.bugstack.mybatis.type.TypeHandler;
import cn.bugstack.mybatis.type.TypeHandlerRegistry;
import com.alibaba.fastjson.JSON;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class DefaultParameterHandler implements ParameterHandler{

    private final TypeHandlerRegistry typeHandlerRegistry;

    private final MappedStatement mappedStatement;
    private final Object parameterObject;
    private BoundSql boundSql;
    private Configuration configuration;

    public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
        this.mappedStatement = mappedStatement;
        this.configuration = mappedStatement.getConfiguration();
        this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
        this.parameterObject = parameterObject;
        this.boundSql = boundSql;
    }


    @Override
    public void setParameters(PreparedStatement ps) throws SQLException {
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if(null != parameterMappings){
            for(int i=0;i<parameterMappings.size();i++){
                ParameterMapping parameterMapping = parameterMappings.get(i);
                String result = parameterMapping.getProperty();
                Object o;
                if(typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())){
                    o = parameterObject;
                }else{
                    MetaObject metaObject =  configuration.newMetaObject(parameterObject.getClass());
                    o = metaObject.getValue(result);
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();

                System.out.println("根据每个ParameterMapping中的TypeHandler设置对应的参数信息 value：{}"+ JSON.toJSONString(o));
                TypeHandler typeHandler = parameterMapping.getTypeHandler();
                typeHandler.setParameter(ps,i+1,o,jdbcType);
            }
        }


    }
}
